package org.jeecg.modules.tencent_esign.tencent_upload.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.tencent_esign.tencent_upload.service.ITencentUploadService;
import org.jeecg.modules.tencent_esign.tencent_upload.utils.TencentEsignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 腾讯电子签文件上传服务实现类
 * @Author: jeecg-boot
 * @Date: 2025-06-28
 * @Version: V1.0
 */
@Service
@Slf4j
public class TencentUploadServiceImpl implements ITencentUploadService {

    @Autowired
    private TencentEsignUtil tencentEsignUtil;

    @Override
    public Result<?> uploadFile(MultipartFile file, String fileType, String fileName, String businessType, JSONObject agent) {
        try {
            // 参数校验
            if (file == null || file.isEmpty()) {
                return Result.error("文件不能为空");
            }

            if (businessType == null || businessType.isEmpty()) {
                return Result.error("业务类型不能为空");
            }

            // 如果未指定文件名，则使用原始文件名
            if (fileName == null || fileName.isEmpty()) {
                fileName = file.getOriginalFilename();
            }

            // 将文件转换为Base64编码
            byte[] fileBytes = file.getBytes();
            String fileBase64 = Base64.encodeBase64String(fileBytes);

            // 构造请求参数
            JSONObject requestParams = tencentEsignUtil.buildUploadFileRequest(fileBase64, fileName, businessType, agent);
            String payload = requestParams.toJSONString();
            
            // 构造请求头 (使用正确的API操作名称)
            Map<String, String> headers = tencentEsignUtil.buildHeaders("UploadFiles", payload);

            // 调用腾讯电子签上传接口
            JSONObject response = uploadToTencentEsign(payload, headers);

            if (response != null && response.getJSONObject("Response") != null) {
                JSONObject resp = response.getJSONObject("Response");
                if (resp.getJSONObject("Error") == null) {
                    // 上传成功
                    int totalCount = resp.getIntValue("TotalCount");
                    String fileId = resp.getJSONArray("FileIds").getString(0);
                    
                    Map<String, Object> resultData = new HashMap<>();
                    resultData.put("fileId", fileId);
                    resultData.put("fileName", fileName);
                    resultData.put("businessType", businessType);
                    resultData.put("totalCount", totalCount);
                    return Result.OK("上传成功", resultData);
                } else {
                    // 上传失败
                    JSONObject error = resp.getJSONObject("Error");
                    return Result.error("上传失败：" + error.getString("Message"));
                }
            } else {
                return Result.error("上传失败：响应数据为空");
            }
        } catch (Exception e) {
            log.error("上传文件到腾讯电子签平台异常", e);
            return Result.error("上传异常：" + e.getMessage());
        }
    }

    /**
     * 上传文件到腾讯电子签平台
     *
     * @param payload 请求参数
     * @param headers 请求头
     * @return
     */
    private JSONObject uploadToTencentEsign(String payload, Map<String, String> headers) {
        try {
            // 创建RestTemplate实例
            RestTemplate restTemplate = new RestTemplate();

            // 设置请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            headers.forEach(httpHeaders::add);

            // 创建请求实体
            HttpEntity<String> entity = new HttpEntity<>(payload, httpHeaders);

            // 发送POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                    "https://file.ess.tencent.cn", entity, String.class);

            // 解析响应
            return JSONObject.parseObject(response.getBody());
        } catch (Exception e) {
            log.error("调用腾讯电子签上传接口异常", e);
            return null;
        }
    }
    
    // 为了兼容原来的接口方法签名
    @Override
    public Result<?> uploadFile(MultipartFile file, String fileType, String fileName) {
        // 创建默认的agent信息
        JSONObject agent = new JSONObject();
        agent.put("AppId", "");
        
        JSONObject proxyOperator = new JSONObject();
        proxyOperator.put("OpenId", "admin");
        agent.put("ProxyOperator", proxyOperator);
        
        // 调用新的方法
        return uploadFile(file, fileType, fileName, "DOCUMENT", agent);
    }
}